﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;
using System.IO;
using System.Diagnostics;

namespace LOGISTCBUS.WebUI.Controllers
{
    public class DocumentController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Search()
        {
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var date = String.IsNullOrEmpty(Request.Params[@"date"]) ? new Nullable<DateTime>() : Convert.ToDateTime(Request.Params[@"date"]);
            var idTrip = String.IsNullOrEmpty(Request.Params[@"idTrip"]) ? 0 : Convert.ToInt32(Request.Params[@"idTrip"]);
            var pageSize = MvcApplication.pageSize;
            var documents = new DocumentDAO().select(date, idTrip, page, pageSize);
            var count = new DocumentDAO().getCount(date, idTrip);
            var totalPages = (count < pageSize) ? 1 : Math.Ceiling(Convert.ToDecimal(count) / pageSize);
            var lst = new List<object>();

            foreach (var d in documents)
            {
                var t = new TripDAO().selectById(d.Trip.Id);
                lst.Add(new
                {
                    Id = d.Id,
                    Name = d.Name,
                    Date = d.Date.HasValue ? Convert.ToDateTime(d.Date).ToString("dd/MM/yyyy") : string.Empty,
                    Trip = t != null ? t.Code : string.Empty
                });
            }

            var obj = new
            {
                data = lst,
                currpage = page,
                totalpages = totalPages,
                totalrecords = count
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete()
        {
            var id = String.IsNullOrEmpty(Request.Params[@"id"]) ? 0 : Convert.ToInt32(Request.Params[@"id"]);
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var aux = true;

            if (id > 0)
            {
                var d = new Document() { Id = id };
                aux = new DocumentDAO().deleteUpdate(d);
            }

            var obj = new
            {
                Message = "Registro removido com sucesso!",
                Success = aux,
                Page = page
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteAll()
        {
            var values = Request.Form["ids"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var aux = true;

            var lst = new List<Document>();
            foreach (var val in values)
                if (!String.IsNullOrEmpty(val))
                    lst.Add(new Document() { Id = Convert.ToInt32(val) });
            aux = new DocumentDAO().deleteUpdate(lst);

            var obj = new
            {
                Message = "Registro(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }

        public ActionResult Download(int id)
        {
            if (id > 0)
            {
                var doc = new DocumentDAO().selectById(id);
                if (doc != null)
                {
                    var fileName = Path.Combine(Server.MapPath("/Files"), doc.Name);
                    byte[] MyData = new byte[0];
                    MyData = FileToByteArray(fileName);
                    int ArraySize = new int();
                    ArraySize = MyData.GetUpperBound(0);

                    FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
                    fs.Write(MyData, 0, ArraySize);
                    fs.Close();

                    Response.Clear();
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Length", MyData.Length.ToString());
                    Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", doc.Name));
                    Response.BinaryWrite(MyData);
                    Response.End();
                }
            }

            return RedirectToAction(@"Index", @"Document");
        }

        public byte[] FileToByteArray(string fileName)
        {
            byte[] _Buffer = null;
            try
            {
                System.IO.FileStream _FileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
                long _TotalBytes = new System.IO.FileInfo(fileName).Length;
                _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }
            catch (Exception _Exception)
            {
                Debug.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }
            return _Buffer;
        }
    }
}
